package com.huitong.oss.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.huitong.api.oss.exception.UploadException;
import com.huitong.oss.properties.OSSCustomProperties;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;

/**
 * 阿里云OSS工具类
 *
 * @author fromdrowning
 * @date 2024/5/20 下午1:36
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class OSSUtils {

    /**
     * {@link OSS}实例
     */
    private static final OSS OSS_CLIENT = SpringUtil.getBean(OSS.class);

    /**
     * {@link OSSCustomProperties}实例
     */
    private static final OSSCustomProperties OSS_PROPERTIES = SpringUtil.getBean(OSSCustomProperties.class);

    /**
     * 文件上传
     *
     * @param fileName 文件名
     * @param file     文件
     * @return 上传云端后文件的访问路径
     * @throws UploadException 文件上传失败抛出此异常
     */
    public static String upload(String fileName, byte[] file) throws UploadException {
        try {
            OSS_CLIENT.putObject(OSS_PROPERTIES.getBucketName(), fileName, new ByteArrayInputStream(file));
        } catch (OSSException e) {
            log.error("阿里云OSS客户端拒绝响应", e);
            throw new UploadException();
        } catch (ClientException e) {
            log.error("连接阿里云OSS客户端异常", e);
            throw new UploadException();
        } finally {
            OSS_CLIENT.shutdown();
        }

        return "https://" + OSS_PROPERTIES.getBucketName() + "." + OSS_PROPERTIES.getEndpoint() + "/" + fileName;
    }
}
